package com.zhenyi.tuangou.core;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.PaymentApi.TradeType;
import com.jfinal.weixin.sdk.kit.PaymentKit;

public class WXPayUtils {

	protected final String APP_ID = PropKit.get("appId");
	protected final String HOST = PropKit.get("host");
	private final String notify_url = PropKit.get("notify_url");
	private final String partnerkey = PropKit.get("partnerkey");
	private final String partner = PropKit.get("partner");

	/**
	 * 退款
	 * 
	 * @param outTradeNo
	 * @param total
	 */
	public void refund(String outTradeNo, int total) {
		
	}

	public Ret pushOrder(String outTradeNo, String total, String ip, String openId) {

		String appId = APP_ID;
		// 统一下单文档地址：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
		Map<String, String> params = new HashMap<String, String>();
		// int total = order.getPrice();
		// total *= 100;
		// total = 1;
		params.put("appid", appId);
		params.put("mch_id", partner);
		params.put("body", "微信支付");
		params.put("out_trade_no", outTradeNo);
		params.put("total_fee", "" + total);

		// String ip = IpKit.getRealIp(getRequest());
		// if (StrKit.isBlank(ip)) {
		// ip = "127.0.0.1";
		// }

		params.put("spbill_create_ip", ip);
		params.put("trade_type", TradeType.JSAPI.name());
		params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
		params.put("notify_url", notify_url);
		params.put("openid", openId);

		String sign = PaymentKit.createSign(params, partnerkey);
		params.put("sign", sign);
		String xmlResult = PaymentApi.pushOrder(params);

		Map<String, String> result = PaymentKit.xmlToMap(xmlResult);

		String return_code = result.get("return_code");
		String return_msg = result.get("return_msg");
		if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
			LogKit.error("return_msg: " + return_msg);
			return Ret.fail();
		}
		String result_code = result.get("result_code");
		if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
			LogKit.error("return_msg: " + return_msg);
			return Ret.fail();
		}
		String prepay_id = result.get("prepay_id");

		// 以下字段在return_code 和result_code都为SUCCESS的时候有返回

		Map<String, String> packageParams = new HashMap<String, String>();
		packageParams.put("appId", appId);
		packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
		packageParams.put("nonceStr", System.currentTimeMillis() + "");
		packageParams.put("package", "prepay_id=" + prepay_id);
		packageParams.put("signType", "MD5");
		String packageSign = PaymentKit.createSign(packageParams, partnerkey);
		packageParams.put("paySign", packageSign);

		Ret ret = Ret.ok();
		ret.set("packageParams", packageParams);
		return ret;
	}
}
